<?php
namespace App\Http\Controllers\Business\Common;

use App\Models\City;
use App\Models\Comment;
use App\Models\Order;
use App\Models\RedEnvelope;
use App\Models\SalesmanRegister;
use App\Models\Shop;
use App\Models\ShopSalesman;
use App\Models\ShopSalesmanDetail;
use App\Models\SalesmanInfo;
use App\Models\SalesmanSet;
use App\Models\SalesmanOrder;
use App\Models\SmsMessage;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Log;

class Common
{
    //收款
    //传人参数为 collectmethod(用户，商家),
    //返回参数为 data: ['status'(1余额不足，2买单成功，3买单次数超过)， ordernumber]
    public static function collectMoney($shopId,$money,$collectionMethod, $userId, $payCode, $shopUserId, $type='') {
        if(!$shopId || !$money ||($money==0)||($money == 0.0)||($money == 0.00)|| !$collectionMethod || !($collectionMethod=='user' || $collectionMethod=='shop') ) {
            return ['status'=>'failed','message'=>'参数错误！'];
        }
        if($collectionMethod == 'user') {
            //用户
            if(!$userId) {
                return ['status'=>'failed','message'=>'参数错误！'];
            }
            $shopUserId = 0;
        } else {
            //商家
            if(!$payCode) {
                return ['status'=>'failed','message'=>'参数错误！'];
            }
            $userId = Redis::get('PayCode:'.$payCode);
            if($userId) {
                Redis::expire('PayCode:' . $payCode, 100);
                Redis::expire('PayCode:Userid:' . $userId, 100);
            }
        }
        $user = User::where('id', $userId)->first();
        $shop = Shop::where('id', $shopId)->first();
        if($user && $shop) {
            //判断是不是超过买单次数限制
            $buyNumber = $shop['buynumber'];
            $maxSales = $shop['maxsales'];
            $cityId = $shop['cityid'];
            if(($maxSales != 0)&&($maxSales != 0.00) && ($maxSales != '')&&($maxSales<$money)) {
                return ['status'=>'failed', 'message'=>'已达封顶金额'.$maxSales];
            }
            if($collectionMethod == 'user') {
                if (self::isBuyNumberExceed($buyNumber, $userId, $shopId)) {
                    //付款失败，超过单日最大消费次数！
                    return ['status' => 'success', 'data' => ['ordernumber' => '', 'status' => '3']];
                }
            } else {
                if (($type == '0') || ($type == '')) {
                    if (self::isBuyNumberExceed($buyNumber, $userId, $shopId)) {
                        return ['status' => 'success', 'data' => ['ordernumber' => '', 'isbuylimit' => '1']];
                    }
                } elseif ($type == '2') {
                    if (self::isBuyNumberExceed($buyNumber, $userId, $shopId)) {
                        Redis::setex('PayCode:' . $payCode, 20, 'buynumberlimit');
                        return ['status' => 'failed', 'message' => '收款失败'];
                    }
                }
            }

            //取出小于订单金额的最大红包金额的红包
            $GLOBALS['cityid'] = $shop->cityid;
            $redEnvelope = RedEnvelope::where('userid',$userId)->where('status','0')->where('amount', '<=', $money)
                ->where(function($query) {
                    $query->orwhere('cityid', $GLOBALS['cityid'])->orwhere('cityid', 0);
                })
                ->where('endtime', '>=', date('Y-m-d'))
                ->orderBy('amount','desc')->orderBy('created_at', 'asc')->first();
            if($redEnvelope) {
                //有红包
                $redEnvelopeAmount =$redEnvelope['amount'];
                $hqAmount = $redEnvelope['hqamount'];
                $agentAmount = $redEnvelope['agentamount'];
                $redEnvelopeId = $redEnvelope['id'];
                if(bccomp($user['balance'], $money-$redEnvelopeAmount, 2) == -1) {
                    //用户余额不足！ 有红包的情况下
                    if($collectionMethod == 'user') {
                        return ['status' => 'success', 'data' => ['ordernumber' => '', 'status' => '1']];
                    } else {
                        Redis::setex('PayCode:'.$payCode,20,'balance is not enough');
                        return ['status'=>'failed','message'=>'用户余额不足！'];
                    }
                }
                $redEnvelope->status = '1';
                $redEnvelope->usetime = date('Y-m-d');
                $redEnvelope->save();
            } else {
                //无红包
                $redEnvelopeAmount = 0;
                $redEnvelopeId = NULL;
                $hqAmount = 0.00;
                $agentAmount = 0.00;
                if(bccomp($user['balance'],$money, 2) == -1) {
                    //用户余额不足！
                    if($collectionMethod == 'user') {
                        return ['status' => 'success', 'data' => ['ordernumber' => '', 'status' => '1']];
                    } else {
                        Redis::setex('PayCode:'.$payCode,20,'balance is not enough');
                        return ['status'=>'failed','message'=>'用户余额不足！'];
                    }
                }
            }

            $isOrder = Order::where('userid',$userId)->first();
            if(!$isOrder) {
                //是否第一次买单
                $user->firstordertime = date('Y-m-d H:i:s',time());
                $user->firstshopname = $shop['name'];
                $user->save();
            }
            //生成订单
            $mobile = substr($user['mobile'],7,10);
            $rand = '';
            for($i=0;$i<4;$i++) {
                $rand .= rand(0,9);
            }
            $orderNumber=date('ymdHis',time()).$rand.$mobile;
            $order = new Order();
            $order->startbalance = User::where('id',$userId)->pluck('balance')->first();
            User::find($userId)->decrement('balance', $money - $redEnvelopeAmount);
            User::find($userId)->increment('savemoney', round(0.5*$money+ $redEnvelopeAmount,2));
            Shop::find($shopId)->increment('ordernumber', 1);
            $order->userid = $userId;
            $order->nickname = $user['nickname'];
            $order->shopid = $shopId;
            $order->shopname = $shop['name'];
            $order->shoplogo = $shop['logo'];
            $order->ordernumber = $orderNumber;
            $order->orderamount = $money;
            $order->shopamount = $money;
            $order->fee = env('COMMISSION_MONEY');
            $order->accountamount = round($money/2,2);
            $order->actualamount = $money - $redEnvelopeAmount + env('COMMISSION_MONEY');
            $order->redenvelopeamount = $redEnvelopeAmount;
            $order->redenvelopeid = $redEnvelopeId;
            $order->lastbalance = User::where('id',$userId)->pluck('balance')->first();
            $order->cityid = $cityId;
            $order->shopuserid = $shopUserId;
            $order->path = $collectionMethod;
            $order->hqamount = $hqAmount;
            $order->agentamount = $agentAmount;
            $order->maintainerid = $shop['maintainerid'];
            $comment = Order::where('userid',$userId)->where('shopid',$shopId)
                ->where('created_at','>',date('Y-m-d 00:00:00',time()))
                ->where('created_at','<',date('Y-m-d 23:59:59',time()))
                ->where('commentstatus','1')->first();
            if($comment) {
                //commentstatus, 0表示未评论，1表示已评论，2表示今天该用户在该商家已评论
                $order->commentstatus = '2';
            }
            $order->save();
            //添加地推信息
            self::addSalesmanByOrder($userId, $order->id, $orderNumber, $money-$redEnvelopeAmount, date('Y-m-d H:i:s'), $cityId);
            //领取新的红包
            if($user->isdouble != 1) {
                //内部用户不给发红包
                $redEnvelopeResult = self::getRedEnvelopAfterOrder($userId, $money - $redEnvelopeAmount, $cityId);
                if ($redEnvelopeResult['status'] == 'success') {
                    $order->bonusid = $redEnvelopeResult['data']['redenvelopeid'];
                    $order->bonus = $redEnvelopeResult['data']['amount'];
                    $order->save();
                }
            }
            if($collectionMethod == 'user') {
                $smsMobileString = $shop['smsphone'];
                //发送短信
                self::sendSmsToShopAfterOrder($smsMobileString, $money);
                //买单成功
                return ['status'=>'success','data'=>['ordernumber'=>$orderNumber, 'status'=>'2']];
            } else {
                Redis::setex('PayCode:'.$payCode,10,$orderNumber);
                Redis::expire('PayCode:Userid:'.$userId,10);
                return ['status'=>'success','data'=>['ordernumber'=>$orderNumber, 'isbuylimit'=>'0']];
            }
        } else {
            return ['status'=>'failed', 'message'=>'系统错误！'];
        }
    }
    //买单次数是否超过次数
    protected static function isBuyNumberExceed($buyNumber, $userId, $shopId) {
        if($buyNumber != 0) {
            $ordercount = Order::where('userid', $userId)->where('shopid', $shopId)->where('created_at', '>=', date('Y-m-d') . " 00:00:00")->get()->count();
            if ($ordercount >= $buyNumber) {
                return true;
            }
        }
        return false;
    }
    //买单以后给商家发送短信
    protected static function sendSmsToShopAfterOrder($smsMobileString, $money) {
        $smsMobileArray = explode(',', $smsMobileString);
        foreach($smsMobileArray as $smsMobile) {
            SmsMessage::collectMoneyToShop($smsMobile,$money);
        }
        return true;
    }
    //买单以后获取的红包金额
    public static function getRedEnvelopAfterOrder($userId, $orderAmount, $cityId) {
        if(!$userId||!$orderAmount||!$cityId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $city = City::where('id', $cityId)->first();
        if(!$city) {
            return ['status'=>'failed', 'message'=>'城市信息错误'];
        }
        $fee = env('RECHARGE_FEE'); //服务费比例
        $agentAmount = floor($orderAmount * $city['agentratio'] * $fee /10)/10; //agentratio是百分比整数。精确到角
        $hqAmount = floor($orderAmount * $city['hqratio'] * $fee /10)/10; //hqratio是百分比，整数
        $amount = floor($orderAmount * $city['ratio'] * $fee /10)/10; //platformratio是百分比，整数
        $validDays = ($city['validdays']>0) ? ($city['validdays']-1) : 0;
        if($amount<1) {
            //小于1元的不给红包
            return ['status'=>'failed', 'message'=>'红包过小'];
        }
        $startTime = date('Y-m-d');
        $endTime = date('Y-m-d', strtotime('+' . $validDays . 'days'));
        $redEnvelope = RedEnvelope::create([
            'userid' => $userId,
            'amount' => $amount,
            'agentamount' => $agentAmount,
            'hqamount' => $hqAmount,
            'starttime' => $startTime,
            'endtime' => $endTime,
            'cityid' => $cityId,
            'status' => 0
        ]);
        $redEnvelope->save();
        $redEnvelopeId = $redEnvelope->id;
        $data = [
            'redenvelopeid' => $redEnvelopeId,
            'amount' => $amount,
            'hqamount' => $hqAmount,
            'agentamount' => $agentAmount,
            'endtime' => $endTime,
        ];
        return ['status'=>'success', 'data'=>$data];
    }
    //新增地推订单
    public static function addSalesmanByOrder($userId, $orderId, $orderNumber, $orderAmount, $orderTime, $cityId) {
        if(!$userId||!$orderId||!$orderNumber||!$orderAmount||!$orderTime||!$cityId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $user = User::where('id', $userId)->select('mobile', 'shopid', 'salesmanid')->first();
        if(!$user) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        $shopId = $user->shopid;
        $mobile = $user->mobile;
        $salesmanId = $user->salesmanid;
        if(($shopId != 0) && ($shopId != '')) {
            //商家地推
            self::addShopSalesmanByOrder($userId, $shopId, $mobile, $orderNumber, $orderAmount, $orderTime);
        } else {
            //用户地推
            if (($salesmanId != 0) && ($salesmanId != '')) {
                self::addUserSalesmanByOrder($userId, $mobile, $orderId, $orderAmount, $salesmanId, $cityId);
            }
        }
        return ['status'=>'success', 'message'=>'新增地推订单成功'];
    }
    //新增商家地推订单
    public static function addShopSalesmanByOrder($userId, $shopId, $mobile, $orderNumber, $orderAmount, $orderTime) {
        if(!$userId||!$shopId||!$mobile||!$orderNumber||!$orderAmount||!$orderTime) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        //检测订单是不是在同一天和同一家商家消费过
        $userIsConsumeResult = self::userIsConsume($userId, $orderNumber);
        if($userIsConsumeResult ['status'] == 'failed') {
            return ['status'=>'failed', 'message'=>$userIsConsumeResult['message']];
        }
        $shopSalesman = ShopSalesman::where('shopid', $shopId)->where('status', 1)
            ->select( 'contractstarttime', 'contractlasttime', 'type')->first();
        if(!$shopSalesman) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        $contractStartTime = $shopSalesman->contractstarttime;
        $contractLastTime = $shopSalesman->contractlasttime;
        $shopSalesmanType = $shopSalesman->type;
        if($shopSalesmanType == 'partner') {
            $getMoney = round($orderAmount*0.01, 2);
        } elseif($shopSalesmanType == 'common') {
            $getMoney = round($orderAmount*0.005, 2);
        } else {
            return ['status'=>'failed', 'message'=>'类型不对'];
        }
        if((strtotime($orderTime) < strtotime($contractStartTime . " 00:00:00")) || (strtotime($orderTime) > strtotime($contractLastTime . " 23:59:59"))) {
            return ['status'=>'failed', 'message'=>'合约到期了'];
        }
        $registerSalesmanDetail = ShopSalesmanDetail::where('mobile', $mobile)->where('type', 'register')->where('getmoney', '>', 0)->first();
        if(!$registerSalesmanDetail) {
            return ['status'=>'failed', 'message'=>'该用户是无效用户'];
        }
        $shopUserId = $registerSalesmanDetail->shopuserid;
        $shopUserMobile = $registerSalesmanDetail->shopusermobile;
        //商家地推详情
        $shopSalesmanDetail = ShopSalesmanDetail::create([
            'shopid' => $shopId,
            'shopusermobile' => $shopUserMobile,
            'shopuserid' => $shopUserId,
            'type' => 'order',
            'mobile' => $mobile,
            'getmoney' => $getMoney,
            'ordernumber' => $orderNumber,
            'orderamount' => $orderAmount,
            'ordertime' => date('Y-m-d H:i:s', strtotime($orderTime))
        ]);
        if($getMoney != 0) {
            ShopSalesman::where('shopid', $shopId)->increment('balance', $getMoney);
            ShopSalesman::where('shopid', $shopId)->increment('validordernum', 1);
            ShopSalesman::where('shopid', $shopId)->increment('getmoney', $getMoney);
        }
        ShopSalesman::where('shopid', $shopId)->increment('ordernum', 1);
        ShopSalesman::where('shopid', $shopId)->increment('totalorderamount', $orderAmount);

        return ['status'=>'success', 'message'=>'新增成功'];
    }
    //新增用户地推订单
    public static function addUserSalesmanByOrder($userId, $mobile, $orderId, $orderAmount,$salesmanId, $cityId) {
        if(!$userId||!$orderId||!$orderAmount||!$salesmanId||!$cityId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        if(!SalesmanRegister::where('registermobile', $mobile)->where('isvalid', 1)->first()) {
            return ['status'=>'failed', 'message'=>'该用户是无效地推用户'];
        }
        $salesmanSetId = SalesmanInfo::where('salesmanid', $salesmanId)->pluck('salesmansetid')->first();
        $salesmanSet = SalesmanSet::where('cityid', $cityId)->where('id', $salesmanSetId)
            ->where('salesmantype', 'usersalesman')->where('status', 1)->first();
        if(!$salesmanSet) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        $accountType = $salesmanSet->accounttype;
        if($accountType == 2) {
            if($orderAmount >= $salesmanSet->accountorderminamount) {
                $getMoney = $salesmanSet->ordergetmoney;
            } else {
                $getMoney = 0;
            }
        } elseif ($accountType == 3) {
            $orderGetRatio = $salesmanSet->ordergetratio;
            $getMoney = round($orderGetRatio*$orderAmount/100, 2);
        } elseif($accountType == 4) {
            $salesmanInfo = SalesmanInfo::where('salesmanid', $salesmanId)->where('status', 1)->first();
            if(!$salesmanInfo) {
                return ['status'=>'failed', 'message'=>'获取信息失败'];
            }
            if($salesmanInfo->registernum < $salesmanSet->topnum) {
                $orderGetRatio = $salesmanSet->topordergetratio;
            } else {
                $orderGetRatio = $salesmanSet->afterordergetratio;
            }
            $orderGetRatio = round($orderGetRatio/100, 2);
            $getMoney = round($orderGetRatio*$orderAmount, 2);
        } else {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        if($getMoney > 0) {
            $isValid = 1;
        } else {
            $isValid = 0;
        }
        $salesmanOrder = SalesmanOrder::create([
            'salesmanid' => $salesmanId,
            'registermobile' => $mobile,
            'registerid' => $userId,
            'orderid' => $orderId,
            'orderamount' => $orderAmount,
            'getmoney' => $getMoney,
            'isvalid' => $isValid,
            'status' => 0,
        ]);
        $salesmanOrder->save();
        SalesmanInfo::where('salesmanid', $salesmanId)->increment('ordernum', 1);
        if($getMoney != 0) {
            SalesmanInfo::where('salesmanid', $salesmanId)->increment('ordervalidnum', 1);
            SalesmanInfo::where('salesmanid', $salesmanId)->increment('ordermoney', $getMoney);
            SalesmanInfo::where('salesmanid', $salesmanId)->increment('totalmoney', $getMoney);
            SalesmanInfo::where('salesmanid', $salesmanId)->increment('balance', $getMoney);
            SalesmanInfo::where('salesmanid', $salesmanId)->increment('currentordernum', 1);
            SalesmanInfo::where('salesmanid', $salesmanId)->increment('currentordertotalamount', $orderAmount);
            SalesmanInfo::where('salesmanid', $salesmanId)->increment('currenttotalmoney', $getMoney);
        }
        SalesmanInfo::where('salesmanid', $salesmanId)->increment('ordertotalamount', $orderAmount);
        return ['status'=>'success', 'message'=>'新增数据成功'];
    }
    //检测订单是不是在同一天和同一家商家消费过
    public static function userIsConsume($userId, $orderNumber) {
        if(!$userId || !$orderNumber) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $order = Order::where('ordernumber', $orderNumber)->where('userid', $userId)->first();
        if(!$order) {
            return ['status'=>'failed', 'message'=>'获取订单失败'];
        }
        $shopId = $order['shopid'];
        $todayStartTime = date('Y-m-d') . " 00:00:00";
        $todayEndTime = date('Y-m-d') . " 23:59:59";
        $count = Order::where('shopid', $shopId)->where('userid', $userId)->where('ordernumber', '!=', $orderNumber)
            ->where('created_at', '>=', $todayStartTime)->where('created_at', '<=', $todayEndTime)
            ->get()->count();
        if($count>0) {
            return ['status'=>'failed', 'message'=>'该用户今天在该商家已买过单'];
        } else {
            return ['status'=>'success', 'message'=>'该用户今天在该商家没买过单'];
        }
    }
}